package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.usian.admin.mapper.LoginMapper;
import com.usian.admin.service.LoginService;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.common.protocol.types.Field;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;

@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, AdUser> implements LoginService {

    @Override
    public ResponseResult login(AdUserDto dto) {
        if(StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"账号或密码不能为空");
        }
        Wrapper<AdUser> Wrapper = new QueryWrapper<>();
        ((QueryWrapper<AdUser>) Wrapper).eq("name",dto.getName());
        List<AdUser> list =list(Wrapper);
        if (list !=null && list.size()==1){
            AdUser adUser = list.get(0);
            String pswd = DigestUtils.md5DigestAsHex((dto.getPassword()+adUser.getSalt()).getBytes());
            if (adUser.getPassword().equals(pswd)){
                HashMap<String, Object> map = Maps.newHashMap();
                adUser.setPassword("");
                adUser.setSalt("");
                map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
                map.put("user",adUser);
                return ResponseResult.okResult(map);
            }else {
                return  ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }else {
            return  ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
    }

//    public static void main(String[] args) {
//        String salt = "123456";
//        String pswd = "yh360204819"+salt;
//        String saltPswd = DigestUtils.md5DigestAsHex(pswd.getBytes());
//        System.out.println(saltPswd);
//    }
}
